<?php

namespace app\components;

/**
 * 参数签名算法
 *
 * @uses      SecurityHelper
 * @version   2016年11月22日
 * @author    lilin <lilin@ugirls.com>
 * @copyright Copyright 2010-2016 北京尤果网文化传媒有限公司
 * @license PHP Version 5.x {@link http://www.php.net/license/3_0.txt}
 */
class SecurityHelper
{
    public static function sign(array $params, $secret)
    {
        if (is_array($params) == false || empty($params) || empty($secret)) {
            throw new \Exception("params is not array or empty OR secret is empty", Errno::SIGN_ERROR);
        }

        $paramsAry = [];
        foreach ($params as $key => $value) {
            $paramsAry[] = "$key=$value";
        }

        sort($paramsAry);
        $paramsStr = implode(",", $paramsAry);

        $keyLen = strlen($secret);
        $md5Str = md5($paramsStr);
        $mdLen = strlen($md5Str);
        $mdLen = $mdLen / 2;

        $sign = "";
        for ($i = 0; $i < $mdLen; $i ++) {
            $ch1 = hexdec($md5Str[$i * 2] . $md5Str[$i * 2 + 1]);
            $ch2 = ord($secret[$i % $keyLen]);
            $ch = ($ch1 ^ $ch2);
            $sign .= $ch <= 0xF ? ('0' . dechex($ch)) : dechex($ch);
        }
        return $sign;
    }

    /**
     * @param array $params
     * @param $secret
     * @param string $signStr 待验证的签名字符串
     * @return bool
     */
    public static function validate(array $params, $secret, $signStr)
    {
        $new = self::sign($params, $secret);

        \App::logger()->debug("SIGN: $new", $params);

        return 0 === strcmp($new, $signStr) ;
    }
}
